import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../components/Layout.vue'
import { useUserStore } from '../store/user'

const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { title: '登录', noAuth: true }
  },
  {
    path: '/',
    component: Layout,
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { title: '仪表盘' }
      },
      {
        path: 'user/list',
        name: 'UserList',
        component: () => import('../views/UserList.vue'),
        meta: { title: '用户列表' }
      },
      {
        path: 'user/roles',
        name: 'UserRoles',
        component: () => import('../views/Home.vue'),
        meta: { title: '角色管理' }
      },
      {
        path: 'content/articles',
        name: 'ContentArticles',
        component: () => import('../views/Article.vue'),
        meta: { title: '文章管理' }
      },
      {
        path: 'content/categories',
        name: 'ContentCategories',
        component: () => import('../views/Home.vue'),
        meta: { title: '分类管理' }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('../views/Article.vue'),
        meta: { title: '系统设置' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
    meta: { title: '404', noAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 从localStorage获取登录状态
  const loginUser = JSON.parse(localStorage.getItem('loginUser') || '{}')
  const isLoggedIn = !!loginUser.token
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 互阅侠管理系统` : '互阅侠管理系统'
  
  // 判断页面是否需要登录权限
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 需要登录但未登录，重定向到登录页
    if (!isLoggedIn) {
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 保存原本要访问的路径
      })
    } else {
      next() // 已登录，放行
    }
  } else {
    // 不需要登录权限的页面直接放行
    // 如果已登录且要访问登录页，重定向到首页
    if (isLoggedIn && to.path === '/login') {
      next({ path: '/' })
    } else {
      next()
    }
  }
})

export default router